<template>
    <div class="honor-picture-container">
        <el-upload
            list-type="picture-card"
            :auto-upload="true"
            :file-list="pictureList"
            :action="uploadPictureUrl"
            :headers="headers"
            name="file"
            accept="image/png, image/jpeg, image/gif"
            ref="pictureUploader"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
        >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                <span class="el-upload-list__item-actions">
                    <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                    >
                        <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                    >
                        <i class="el-icon-download"></i>
                    </span>
                    <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                    >
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth"
import {
    addPicture, updatePictures,
    getHonorPictures, deleteHonorPicture
} from "@/api/archive-honor/honor";

export default {
    name: 'HonorPicture',
    props: {
        model: Object,
        rules: Object
    },
    data () {
        return {
            pictureType: 1,
            pictureList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            headers: {
                Authorization: "Bearer " + getToken(),
            }
        };
    },
    computed: {
        uploadPictureUrl () {
            return this.pictureType
                ? (process.env.VUE_APP_BASE_API + "/common/upload/" + this.pictureType)
                : (process.env.VUE_APP_BASE_API + "/common/upload")
        }
    },
    methods: {
        handleRemove (file) {
            console.log(file);
        },
        handlePreview (file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload (file) {
            console.log(file);
        },
        handlePictureCardPreview (file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        loadPictures (honorModel) {
            // console.log('honorModel=:', honorModel)
            if (honorModel.pictures) {
                var pictures = JSON.parse(honorModel.pictures)
                console.log('后台返回的图片：', pictures)
                for (let i = 0; i < pictures.length; i++) {
                    this.pictureList.push({
                        id: pictures[i].pictureId,
                        label: pictures[i].originalFilename,
                        url: 'http://localhost:8080' + pictures[i].virtualPath,
                    });
                }
            } else {
                this.pictureList = []
            }
        },
        async uploadSuccess (res, file, fileList) {
            if (res.code !== 200) {
                this.$message.error(res.msg)
                return;
            }
            //console.log('返回结果...', res)
            //console.log('已经上传到服务器...', this.pictureList)
            const filename = res.picture.originalFilename
            if (!filename) {
                return
            }

            const postData = {
                mimeType: res.picture.mimeType,
                originalFilename: res.picture.originalFilename,
                // seoFilename: null, 
                // altAttribute: null, 
                // titleAttribute: null, 
                virtualPath: res.picture.virtualPath,
                url: res.url,
                // size: 356013, 
                honorId: this.model.honorId,
                // displayOrder: this.maxDisplayOrder + 1,
                pictureType: 1
            }
            // 更新荣誉图片字段（添加荣誉图片）
            const result = await addPicture(postData)
            if (result.code === 200) {
                this.$emit('pictureChange', result.msg)
                console.log('上传的图片为：', result)
            }

            // const pictureModel = {
            //     name: filename,
            //     url: res.url, // URL.createObjectURL(file.raw)
            //     pictureId: picture.pictureId,
            //     productPictureId: picture.productPictureId,
            //     productId: picture.productId,
            //     displayOrder: picture.displayOrder
            // }
            // this.$emit('onAdd', pictureModel)
            // // 使用 push方法会造成 闪动
            // // this.pictureList.push(pictureModel)
            // // 这里 hack 一下，不知行不行
            // const len = this.pictureList.length
            // this.pictureList.length = len + 1
            // this.pictureList[len] = pictureModel

            // this.pictureListModel.push(pictureModel)
            // console.log('pictureList=', this.pictureList)
        },
        beforeUpload (file) {
            // console.log('beforeUpload:', file)
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG / png 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    }
}
</script>

<style scoped lang="scss">
// .honor-picture-container {
//     margin-left: 20px;
// }
// .el-upload-list__item-actions {
//     display: flex;
//     margin-left: 30px;
//     width: 300px;
//     height: 70px;
//     line-height: 70px;

//     align-items: center;
//     justify-content: space-around;
// }
</style>
